package com.ericsson.enap.modules.backup.service.impl;

import cn.hutool.extra.ssh.JschUtil;
import com.ericsson.common.util.FileSizeHelper;
import com.ericsson.common.util.FileUtil;
import com.ericsson.enap.modules.backup.utils.VgcBackupSshUtil;
import com.ericsson.enap.modules.backup.constant.BackupConstant;
import com.ericsson.enap.modules.backup.mapper.ImsDataBackupMapper;
import com.ericsson.enap.modules.backup.service.VgcDataBackupService;
import com.ericsson.enap.modules.backup.utils.VgcBackupUtil;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.mapper.EpcDictMapper;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import com.ericsson.epc.modules.backup.utils.EpcBackupUtil;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;

import static com.ericsson.enap.modules.backup.constant.BackupConstant.*;

/**
 * @description: VgcDataBackupServiceImpl服务实现类
 * @author: wangjingshi
 * @create: 2021-09-03 09:12
 */
@Service
public class VgcDataBackupServiceImpl implements VgcDataBackupService {

    @Autowired
    private ImsDataBackupMapper imsDataBackupMapper;
    @Autowired
    private EpcDictMapper epcDictMapper;

    @Override
    public List<EnipNetelement> queryNetelementList(int bizType, String collectorIp) {
        return imsDataBackupMapper.queryNetelementList(bizType,collectorIp);
    }

    @Override
    public void deleteOldData(String cleanDate) {
        imsDataBackupMapper.deleteOldData(cleanDate);
    }


    private void zipDelAndInsertDB(EnipNetelement vgcNet, String filePath, String fileType) {
        String cmd = "zip -r " + filePath + fileType + ".zip" + " "+fileType;
        EpcBackupUtil.executeZipCmd(cmd, vgcNet.getName(),new File(filePath));
        File file = new File(filePath + fileType+".zip");
        String fileSize = FileSizeHelper.getHumanReadableFileSize(file.length());
        FileUtil.deleteDir(new File(filePath+fileType));
        imsDataBackupMapper.insertBackupTable(filePath,fileType+".zip", vgcNet.getName(), vgcNet.getId(),Long.valueOf(vgcNet.getType()),fileSize,fileType);
    }

    @Override
    public void execAmfBackup(EnipNetelement amf, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + amf.getType() + "/" + amf.getName() + "/";
        VgcBackupSshUtil ssh = new VgcBackupSshUtil(amf.getIp4(), amf.getUsername(), amf.getPassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(amf.getName()+" ==== amf backup:gsh export_config_active");
            String res = ssh.sendCommandV2("gsh export_config_active", hash,2);
            log.info(amf.getName()+" ==== amf backup cmd result:" + res);
            res = res.substring(res.indexOf("/"),res.indexOf(mmeKey)).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
            log.info(amf.getName()+" ==== amf backup cmd result:" + res);
            log.info(amf.getName()+" ==== amf backup :" + "cat "+res+mmeKey);
            String result = ssh.sendCommandV3("cat "+res+mmeKey, "ANCB ~ #");
            System.out.println("---- 1 ---- result:"+result.length());
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(amf, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execAmfLog(EnipNetelement amf, String date, Logger log) {
        String area = epcDictMapper.selectEpcDict(new EpcDict("logo")).getKeyValue();
        //甘肃电信特殊情况，这里需要用其他的账号密码
        if(area.contains("gansu")){
            amf.setUsername("om_admin");
            amf.setPassword("Noc@ydz2019");
        }
        if(area.contains("henan")){
            amf.setUsername(amf.getRootUsername());
            amf.setPassword(amf.getRootPwd());
        }
        String filePath = BackupConstant.localPath + date + "/" + amf.getType() + "/" + amf.getName()+"/";
        FileUtil.newDirs(filePath+"security");
        VgcBackupUtil.downloadLogBySftp(amf, filePath,"/tmp/DPE_CORE/seclog/","security",log);
        zipDelAndInsertDB(amf, filePath,"security");
        FileUtil.newDirs(filePath+"cli_log");
        VgcBackupUtil.downloadLogBySftp(amf, filePath,"/logs/cli_log/ready/","cli_log",log);
        zipDelAndInsertDB(amf, filePath,"cli_log");
    }

    @Override
    public void execCgBackup(EnipNetelement cg, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + cg.getType() + "/" + cg.getName() + "/";
        try {
            Session session = JschUtil.getSession(cg.getIp4(), 22, cg.getUsername(), cg.getPassword());
            log.info(cg.getName()+" ==== cg backup:cat /etc/mediation/MM.config");
            String result = JschUtil.exec(session,"cat /etc/mediation/MM.config", Charset.forName("UTF-8"));
            JschUtil.close(session);
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(cg, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {

        }
    }

    @Override
    public void execCgLog(EnipNetelement cg, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + cg.getType() + "/" + cg.getName() + "/";
        VgcBackupSshUtil ssh = new VgcBackupSshUtil(cg.getIp4(), cg.getUsername(), cg.getPassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(cg.getName()+" ==== cg Log:history");
            String history = ssh.sendCommandV2("history", dollar,2);
            System.out.println("========history:"+history);
            EpcBackupUtil.writeNewFile("history.log",history,filePath+"history/");
            zipDelAndInsertDB(cg, filePath,"history");
            String area = epcDictMapper.selectEpcDict(new EpcDict("logo")).getKeyValue();
            //甘肃电信:先普通用户登入，再执行su root,再执行last
            String last = "";
            if(area.contains("gansu")||area.contains("henan")){
                String suRoot = ssh.sendCommandV2("su root", colon,1);
                System.out.println("===========su root:"+suRoot);
                ssh.onlySendCommand(cg.getRootPwd());
                //System.out.println("===========su root pwd:"+suRootPwd);
                System.out.println("===============send last=========");
                last = ssh.sendCommandV2("last", hash,2);
            }else if(area.contains("shanxi")){//山西电信:直接root用户登入，再执行sudo last
                Session session = JschUtil.getSession(cg.getIp4(), 22, cg.getRootUsername(), cg.getRootPwd());
                log.info(cg.getName()+" ==== cg Log:sudo last");
                last = JschUtil.exec(session,"sudo last", Charset.forName("UTF-8"));
                JschUtil.close(session);
                log.info(cg.getName()+" ==== cg Log:sudo last");
            }
            System.out.println("========last:"+last);
            EpcBackupUtil.writeNewFile("last.log",last,filePath+"last/");
            zipDelAndInsertDB(cg, filePath,"last");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execSmfBackup(EnipNetelement smf, String date, Logger log) {
        VgcBackupSshUtil ssh = new VgcBackupSshUtil(smf.getIp4(), smf.getUsername(), smf.getPassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(smf.getName()+" ==== smf or pmf backup:start shell");
            ssh.sendCommandV2("start shell", hash,1);
            ssh.sendCommandV2("start shell", dollar,1);
            /*log.info(saegw.getFname()+" ==== saegw backup:cat /flash/ericsson.xml");
            String result = ssh.sendCommandV3("cat /flash/ericsson.xml", "bash-4.3$");*/
            log.info(smf.getName()+" ==== smf or pmf backup:cp /flash/ericsson.xml /flash/saegw-backup.cfg");
            //ssh.sendCommandV3("cp /flash/ericsson.xml /flash/saegw-backup.cfg", "bash-4.3$");
            /*EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(saegw, filePath,"config");*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execSmfLog(EnipNetelement smf, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + smf.getType() + "/" + smf.getName()+"/";
        FileUtil.newDirs(filePath+"config");
        VgcBackupUtil.downloadLogBySftp(smf, filePath,"/flash/","config",log);
        zipDelAndInsertDB(smf, filePath,"config");
        String area = epcDictMapper.selectEpcDict(new EpcDict("logo")).getKeyValue();
        if(area.contains("henan")){
            smf.setUsername("bfwhxt");
            smf.setPassword("1hblsqT!");
        }
        FileUtil.newDirs(filePath+"audit");
        VgcBackupUtil.downloadLogBySftp(smf, filePath,"/md/","audit",log);
        zipDelAndInsertDB(smf, filePath,"audit");

        FileUtil.newDirs(filePath+"auth");
        VgcBackupUtil.downloadLogBySftp(smf, filePath,"/var/log","auth",log);
        zipDelAndInsertDB(smf, filePath,"auth");
    }

    @Override
    public void execPcfBackup(EnipNetelement pcf, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + pcf.getType() + "/" + pcf.getName() + "/";
        VgcBackupSshUtil ssh = new VgcBackupSshUtil(pcf.getIp4(), pcf.getUsername(), pcf.getPassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();

            log.info(pcf.getName()+" ==== pcf backup:cmw-status -v siass|grep -A2 com|grep SC-1 -A1");
            String area = epcDictMapper.selectEpcDict(new EpcDict("logo")).getKeyValue();
            String ssh_result = "";
            if(area.contains("gansu")){//甘肃电信情况，里面符号是#号，count是2
                if(pcf.getUsername().equals("root")){//root账号的#，非root账号是~>
                    String res = ssh.sendCommandV3("cmw-status -v siass|grep -A2 com|grep SC-1 -A1", "#",2);
                    log.info(pcf.getName()+" ==== pcf backup result:"+res);
                    String name = res.contains("ACTIVE")?"SC-1":"SC-2";
                    log.info(pcf.getName()+" ==== pcf backup:"+"ssh "+name);
                    ssh_result = ssh.sendCommandV3("ssh " + name,"#",1);
                }else{
                    String res = ssh.sendCommandV3("cmw-status -v siass|grep -A2 com|grep SC-1 -A1", "~>",2);
                    log.info(pcf.getName()+" ==== pcf backup result:"+res);
                    String name = res.contains("ACTIVE")?"SC-1":"SC-2";
                    log.info(pcf.getName()+" ==== pcf backup:"+"ssh "+name);
                    ssh_result = ssh.sendCommandV3("ssh " + name,"~>",1);
                }
            }else if(area.contains("shanxi")||area.contains("henan")){//山西电信情况，里面符号是~>,count是3
                String res = ssh.sendCommandV3("cmw-status -v siass|grep -A2 com|grep SC-1 -A1", "~>",3);
                log.info(pcf.getName()+" ==== pcf backup result:"+res);
                String name = res.contains("ACTIVE")?"SC-1":"SC-2";
                log.info(pcf.getName()+" ==== pcf backup:"+"ssh "+name);
                ssh_result = ssh.sendCommandV3("ssh " + name,"~>",1);
            }
            log.info(pcf.getName()+" ==== pcf backup ssh_result:"+ssh_result);
            /*log.info(pcf.getName()+" ==== pcf backup:"+pcf.getPassword());
            ssh.sendCommandV4(pcf.getPassword(),"~>",1);*/
            log.info(pcf.getName()+" ==== pcf backup:cliss");
            /*String cliss_result = ssh.sendCommandV2("cliss",">",2);
            log.info(pcf.getName()+" ==== pcf backup cliss_result:"+cliss_result);*/
            ssh.onlySendCommand("cliss");
            String arr[] = {"show-config","exit","exit","exit"};
            log.info(pcf.getName()+" ==== pcf backup:show-config");
            String result = ssh.sendCommands(arr);
            System.out.println("result:"+result.length());
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(pcf, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execPcfLog(EnipNetelement pcf, String date, Logger log) {
        String filePath = BackupConstant.localPath + date + "/" + pcf.getType() + "/" + pcf.getName() + "/";
        VgcBackupSshUtil ssh = new VgcBackupSshUtil(pcf.getIp4(), pcf.getUsername(), pcf.getPassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(pcf.getName()+" ==== pcf Log:last");
            String area = epcDictMapper.selectEpcDict(new EpcDict("logo")).getKeyValue();
            String last = "";
            if(area.contains("gansu")){//甘肃电信情况，里面符号是#号，count是2
                if(pcf.getUsername().equals("root")) {//root账号的#，非root账号是~>
                    last = ssh.sendCommandV2("last", hash,2);
                }else{
                    last = ssh.sendCommandV2("last", gt,2);
                }
            }else if(area.contains("shanxi")||area.contains("henan")){//山西电信情况，里面符号是>,count是2
                last = ssh.sendCommandV2("last", gt,2);
            }
            EpcBackupUtil.writeNewFile("last.log",last,filePath+"last/");
            zipDelAndInsertDB(pcf, filePath,"last");
            /*log.info(pcf.getName()+" ==== pcf Log:su -");
            ssh.sendCommandV2("su -", colon,1);
            log.info(pcf.getName()+" ==== pcrf Log:"+pcf.getPassword());
            ssh.sendCommandV4(pcf.getPassword(),hash,1);*/
            log.info(pcf.getName()+" ==== pcrf Log:history");
            String history = "";
            if(area.contains("gansu")){//甘肃电信情况，里面符号是#号，count是2
                if(pcf.getUsername().equals("root")) {//root账号的#，非root账号是~>
                    history = ssh.sendCommandV2("history", hash,2);
                }else{
                    history = ssh.sendCommandV2("history", gt,2);
                }
            }else if(area.contains("shanxi")||area.contains("henan")){//山西电信情况，里面符号是>,count是2
                history = ssh.sendCommandV2("history", gt,2);
            }
            EpcBackupUtil.writeNewFile("history.log",history,filePath+"history/");
            zipDelAndInsertDB(pcf, filePath,"history");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }


}
